package com.fingard.avatar.website.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.fingard.avatar.website.exception.BizException;
import com.fingard.avatar.website.model.bean.LoginResp;
import com.fingard.avatar.website.model.bean.ResultContext;
import com.fingard.avatar.website.model.dto.ExperienceApplyAddDto;
import com.fingard.avatar.website.model.dto.LoginDto;
import com.fingard.avatar.website.service.ExperienceApplyService;
import com.fingard.avatar.website.service.LoginLogService;
import com.fingard.avatar.website.service.UserAuthService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 徐一涛
 * @date 2022-04-26
 */
@Slf4j
@RestController
@RequestMapping("public")
@Api(tags = "")
public class PublicController {

    @Resource
    protected UserAuthService authService;
    @Resource
    protected LoginLogService logService;
    @Resource
    protected ExperienceApplyService applyService;

    @PostMapping("/login")
    public ResultContext<LoginResp> login(@Validated LoginDto req, HttpServletRequest request) {
        String ip = ServletUtil.getClientIP(request);
        LoginResp resp;
        try {
            resp = authService.login(req.getUserName(), req.getPassword());
            logService.add(ip, req.getUserName(), "登录成功");
        } catch (BizException e) {
            logService.add(ip, req.getUserName(), e.getMsg());
            throw e;
        } catch (Exception e) {
            logService.add(ip, req.getUserName(), StrUtil.sub(e.getMessage(), 0, 255));
            throw BizException.of(e.getMessage());
        }
        return ResultContext.success(resp);
    }

    @PostMapping("/experienceApply")
    public ResultContext<Boolean> experienceApply(@Validated ExperienceApplyAddDto req) {
        return ResultContext.success(applyService.add(req));
    }
}
